/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.lecture.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.course.service.EduCourseService;
import vip.xiaonuo.biz.modular.klass.entity.EduKlass;
import vip.xiaonuo.biz.modular.klass.service.EduKlassService;
import vip.xiaonuo.biz.modular.tutorial.entity.EduTutorial;
import vip.xiaonuo.biz.modular.tutorial.enums.EduTutorialStateEnum;
import vip.xiaonuo.biz.modular.tutorial.service.EduTutorialService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.lecture.entity.EduLecture;
import vip.xiaonuo.biz.modular.lecture.mapper.EduLectureMapper;
import vip.xiaonuo.biz.modular.lecture.param.EduLectureAddParam;
import vip.xiaonuo.biz.modular.lecture.param.EduLectureEditParam;
import vip.xiaonuo.biz.modular.lecture.param.EduLectureIdParam;
import vip.xiaonuo.biz.modular.lecture.param.EduLecturePageParam;
import vip.xiaonuo.biz.modular.lecture.service.EduLectureService;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 开课Service接口实现类
 *
 * @author ahui
 * @date  2023/05/13 21:21
 **/
@Service
public class EduLectureServiceImpl extends ServiceImpl<EduLectureMapper, EduLecture> implements EduLectureService {
    @Resource
    private EduCourseService eduCourseService;

    @Resource
    private EduKlassService eduKlassService;

    @Resource
    private EduTutorialService eduTutorialService;

    @Override
    public Page<EduLecture> page(EduLecturePageParam eduLecturePageParam) {
        QueryWrapper<EduLecture> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(eduLecturePageParam.getCourseId())) {
            queryWrapper.lambda().eq(EduLecture::getCourseId, eduLecturePageParam.getCourseId());
        }
        if(ObjectUtil.isNotEmpty(eduLecturePageParam.getTeacherId())) {
            queryWrapper.lambda().eq(EduLecture::getTeacherId, eduLecturePageParam.getTeacherId());
        }
        if(ObjectUtil.isNotEmpty(eduLecturePageParam.getKlassId())) {
            queryWrapper.lambda().like(EduLecture::getKlasses, eduLecturePageParam.getKlassId());
        }
        if(ObjectUtil.isNotEmpty(eduLecturePageParam.getFromWeek())) {
            queryWrapper.lambda().eq(EduLecture::getFromWeek, eduLecturePageParam.getFromWeek());
        }
        if(ObjectUtil.isNotEmpty(eduLecturePageParam.getToWeek())) {
            queryWrapper.lambda().eq(EduLecture::getToWeek, eduLecturePageParam.getToWeek());
        }
        if(ObjectUtil.isNotEmpty(eduLecturePageParam.getState())) {
            queryWrapper.lambda().eq(EduLecture::getState, eduLecturePageParam.getState());
        }
        if(ObjectUtil.isAllNotEmpty(eduLecturePageParam.getSortField(), eduLecturePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(eduLecturePageParam.getSortOrder());
            queryWrapper.orderBy(true, eduLecturePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(eduLecturePageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(EduLecture::getId);
        }
        Page<EduLecture> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        List<EduLecture> records = page.getRecords();
        for (EduLecture lecture: records) {
            String klasses = lecture.getKlasses();
            List<String> klassIds = Arrays.stream(klasses.replaceAll("[\\[\\]\"]", "").split(","))
                    .map(String::trim) // 去掉空格
                    .collect(Collectors.toList());
            List<EduKlass> eduKlasses = eduKlassService.listByIds(klassIds);
            lecture.setKlassName(eduKlasses.stream().map(EduKlass::getName).collect(Collectors.joining(",")));
        }
        page.setRecords(records);
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(EduLectureAddParam eduLectureAddParam) {
        EduLecture eduLecture = BeanUtil.toBean(eduLectureAddParam, EduLecture.class);
        this.save(eduLecture);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(EduLectureEditParam eduLectureEditParam) {
        EduLecture eduLecture = this.queryEntity(eduLectureEditParam.getId());
        BeanUtil.copyProperties(eduLectureEditParam, eduLecture);
        this.updateById(eduLecture);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<EduLectureIdParam> eduLectureIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(eduLectureIdParamList, EduLectureIdParam::getId));
        for (EduLectureIdParam eduLectureIdParam: eduLectureIdParamList) {
            Map<String, Object> map = new HashMap<>();
            map.put("lecture_id", eduLectureIdParam.getId());
            List<EduTutorial> eduTutorials = eduTutorialService.listByMap(map);
            for (EduTutorial eduTutorial: eduTutorials) {
                eduTutorial.setLectureId(null);
                eduTutorial.setState(EduTutorialStateEnum.DOING.getValue());
                eduTutorialService.updateById(eduTutorial);
            }
        }
    }

    @Override
    public EduLecture detail(EduLectureIdParam eduLectureIdParam) {
        return this.queryEntity(eduLectureIdParam.getId());
    }

    @Override
    public EduLecture queryEntity(String id) {
        EduLecture eduLecture = this.getById(id);
        if(ObjectUtil.isEmpty(eduLecture)) {
            throw new CommonException("开课不存在，id值为：{}", id);
        }
        return eduLecture;
    }

    @Override
    public List<EduLecture> listScheduled() {
        Map<String, Object> map = new HashMap<>();
        map.put("STATE", "1");
        return listByMap(map);
    }
}
